package m202406.d05;

import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

/**
 * @@author: 爱做梦的锤子
 * @date: 2024/6/5 13:42
 */
//(C卷,200分)- 亲子游戏
public class C200_02 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int n = scanner.nextInt();

        int[][] matrix = new int[n][n];
        int[][] search = new int[n][n];

        int[] start = new int[2];

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                matrix[i][j] = scanner.nextInt();
                if (matrix[i][j] == -3) {
                    start[0] = i;
                    start[1] = j;
                }
                search[i][j] = -1;
            }
        }
        LinkedList<int[]> list = new LinkedList<>();
        list.add(start);
        matrix[start[0]][start[1]] = 0;
        search[start[0]][start[1]] = 0;
        System.out.println(travel(matrix, search, list, n));
    }

    private static int travel(int[][] matrix, int[][] search, LinkedList<int[]> start, int n) {
        LinkedList<int[]> nextStart = new LinkedList<>();
        if (start.isEmpty()) {
            return -1;
        }
        while (!start.isEmpty()) {
            int[] ints = start.removeLast();
            int row = ints[0];
            int col = ints[1];
            if (matrix[row][col] == -2) {
                return max(row, col, search, n);
            }
            search[row][col] = Math.max(max(row, col, search, n) + matrix[row][col], 0);
            if (row + 1 < n && matrix[row + 1][col] != -1 && search[row + 1][col] == -1) {
                nextStart.add(new int[]{row + 1, col});
            }
            if (row - 1 >= 0 && matrix[row - 1][col] != -1 && search[row - 1][col] == -1) {
                nextStart.add(new int[]{row - 1, col});
            }
            if (col + 1 < n && matrix[row][col + 1] != -1 && search[row][col + 1] == -1) {
                nextStart.add(new int[]{row, col + 1});
            }
            if (col - 1 >= 0 && matrix[row][col - 1] != -1 && search[row][col - 1] == -1) {
                nextStart.add(new int[]{row, col - 1});
            }
        }
        return travel(matrix, search, nextStart, n);
    }

    private static int max(int row, int col, int[][] search, int n) {
        int max = -1;
        if (row + 1 < n) {
            max = Math.max(max, search[row + 1][col]);
        }
        if (row - 1 >= 0) {
            max = Math.max(max, search[row - 1][col]);
        }
        if (col + 1 < n) {
            max = Math.max(max, search[row][col + 1]);
        }
        if (col - 1 >= 0) {
            max = Math.max(max, search[row][col - 1]);
        }
        return max;
    }
}
